package com.cnswhy.cloud.server.app.controller.cps;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.entity.constant.CnswhyConstant;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.BankCardType;
import com.cnswhy.cloud.server.common.entity.enumeration.ChannelType;
import com.cnswhy.cloud.server.common.entity.enumeration.OrderReportType;
import com.cnswhy.cloud.server.common.entity.mq.CpsOrderQueryMQ;
import com.cnswhy.cloud.server.common.entity.mq.OrderReportMQ;
import com.cnswhy.cloud.server.core.channel.hcpay.dto.*;
import com.cnswhy.cloud.server.core.channel.hcpay.entity.ResponseEntity;
import com.cnswhy.cloud.server.core.channel.hcpay.service.HcpayService;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.oem.SystemService;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.CpsBankRateService;
import com.cnswhy.cloud.server.core.service.CpsBankRateSplitService;
import com.cnswhy.cloud.server.core.service.CpsTransOrderService;
import com.cnswhy.cloud.server.core.service.CustomerDeviceInfoService;
import com.cnswhy.cloud.server.core.service.cps.CpsChannelInfoService;
import com.cnswhy.cloud.server.core.service.cps.CpsCustomerChannelInfoService;
import com.cnswhy.cloud.server.core.service.customer.CustomerBankService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.service.merchant.MerchantService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@Slf4j

@Api(tags = "聚合支付")
@Controller
@RequestMapping("/cps")
public class CpsController extends BaseController {

    @Autowired
    private RedisService redisService;
    @Autowired
    IdGeneratorService idGeneratorService;
    @Autowired
    CustomerBankService customerBankService;
    @Autowired
    SystemService systemService;
    @Autowired
    CpsCustomerChannelInfoService cpsCustomerChannelInfoService;
    @Autowired
    CpsChannelInfoService cpsChannelInfoService;
    @Autowired
    CpsBankRateService cpsBankRateService;
    @Autowired
    CpsBankRateSplitService cpsBankRateSplitService;
    @Autowired
    CpsTransOrderService cpsTransOrderService;
    @Autowired
    HcpayService hcpayService;
    @Autowired
    MessageService messageService;
    @Autowired
    CustomerDeviceInfoService customerDeviceInfoService;
    @Autowired
    CustomerService customerService;
    @ApiOperation(value = "查询分页数据", httpMethod = "POST")
    @ApiParam(name = "bo", value = "查询Bo")
    @RequestMapping("/ajaxBankData")
    @ResponseBody
    public RespVo ajaxBankData(HttpServletRequest request,
                               @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, CustomerBank bo) {
        log.info("查询银行卡信息：{} {} {}", JSON.toJSONString(bo), currentPage, currentPage);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            bo.setCustomerId(loginCustomer.getId());
            bo.setCardType(BankCardType.CREDIT_CARD.getVal());
            QueryWrapper<CustomerBank> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_time");
            Page<CustomerBank> page = new Page<>(currentPage, pageSize);
            IPage<CustomerBank> pageList = customerBankService.page(page, queryWrapper);
            /*pageList.setRecords(pageList.getRecords().stream().map(
                    x ->{
                       return x;
                    }
            ).collect(Collectors.toList()));*/
            for(CustomerBank customerBank : pageList.getRecords()){
                CpsBankRate cpsBankRate = cpsBankRateService.getOne(Wraps.<CpsBankRate>lbQ().eq(CpsBankRate::getBankAbbr,customerBank.getBankAbbr()).eq(CpsBankRate::getChannelType,ChannelType.LARGE));
                if(cpsBankRate == null){
                    cpsBankRate = cpsBankRateService.getOne(Wraps.<CpsBankRate>lbQ().eq(CpsBankRate::getBankAbbr,"OTHER").eq(CpsBankRate::getChannelType,ChannelType.LARGE));
                    if(cpsBankRate == null){
                        throw new BizException("该银行费率未设定");
                    }
                }
                customerBank.setFeeRate(cpsBankRate.getFeeRate());
                customerBank.setExternFee(cpsBankRate.getExternFee());
            }
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询银行卡信息失败");
            log.error("查询银行卡信息失败", e);
        }
        return vo;
    }
    @ApiOperation(value = "查询分页数据", httpMethod = "POST")
    @ApiParam(name = "bo", value = "查询Bo")
    @RequestMapping("/ajaxCpsData")
    @ResponseBody
    public RespVo ajaxCpsData(HttpServletRequest request,
                               @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, CpsTransOrder bo) {
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            bo.setCustomerId(loginCustomer.getId());
            QueryWrapper<CpsTransOrder> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_time");
            Page<CpsTransOrder> page = new Page<>(currentPage, pageSize);
            IPage<CpsTransOrder> pageList = cpsTransOrderService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询订单信息失败");
            log.error("查询订单信息失败", e);
        }
        return vo;
    }
    @ApiOperation(value = "查询渠道列表", httpMethod = "POST")
    @RequestMapping("/queryChannelInfo")
    @ResponseBody
    public RespVo queryChannelInfo(HttpServletRequest request) {
        RespVo vo = new RespVo();
        try {
            vo.setResult(RespVo.CODE_SUCCESS);
            vo.setMessage("成功");
            vo.setResult(cpsChannelInfoService.list(Wraps.<CpsChannelInfo>lbQ().eq(CpsChannelInfo::getStatus,1)));
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("申请订单失败");
            log.error("申请订单失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "订单确认", httpMethod = "POST")
    @RequestMapping("/confirm")
    @ResponseBody
    public RespVo confirm(HttpServletRequest request,String orderId,String smsCode) {
        RespVo vo = new RespVo();
        try{
            CpsTransOrder cpsTransOrder =(CpsTransOrder) redisService.hget("cps.createQrcode" , orderId);
            if(cpsTransOrder == null){
                throw new BizException("订单已过期，请重新下单");
            }
            cpsTransOrder.setStatus(1);
            cpsTransOrderService.updateById(cpsTransOrder);

            CpsChannelInfo cpsChannelInfo = cpsChannelInfoService.getOne(Wraps.<CpsChannelInfo>lbQ().eq(CpsChannelInfo::getChannelId,cpsTransOrder.getChannelId()));
            ResponseEntity responseEntity = hcpayService.subPayConfirm(SubPayConfirmDto.builder()
                    .orderId(idGeneratorService.genCommonIdString())
                    .origOrderId(orderId)
                    .smsCode(smsCode)
                    .subMerchId(cpsTransOrder.getSubMerchId()).build(),cpsChannelInfo.getChannelMerchId(),cpsChannelInfo.getChannelMerchPrivateKey());
            JSONObject jsonObject = JSON.parseObject(responseEntity.getData());
            if("0001".equals(jsonObject.getString("respCode"))){
                JSONObject object = new JSONObject();
                object.put("orderStatus","01");
                object.put("respCode","0001");
                object.put("respDesc",jsonObject.getString("respDesc"));
                cpsTransOrder.setStatus(3);
                cpsTransOrder.setRespCode("0001");
                cpsTransOrder.setRespDesc(jsonObject.getString("respDesc"));
                cpsTransOrderService.updateById(cpsTransOrder);
                return RespVo.fail(jsonObject.getString("respDesc"));
            }
            CpsOrderQueryMQ cpsOrderQueryMQ = CpsOrderQueryMQ.builder()
                    .cpsId(cpsTransOrder.getId())
                    .queryTimes(0L).build();
            messageService.sendAndQueryTimes(AmqpExchange.CPS_ORDER_QUERY_MESSAGE, cpsOrderQueryMQ, cpsOrderQueryMQ.getQueryTimes());

            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("交易处理中，请稍后查看账单");
        } catch (BizException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getMessage());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("订单短信申请");
            log.error("订单短信申请", e);
        }
        return vo;
    }
    @ApiOperation(value = "二维码订单查询", httpMethod = "POST")
    @RequestMapping("/queryCode")
    @ResponseBody
    public RespVo queryCode(HttpServletRequest request,String orderId) {
        RespVo vo = new RespVo();
        try {
            CpsTransOrder cpsTransOrder = (CpsTransOrder) redisService.hget("cps.createQrcode" , orderId);
            if(cpsTransOrder == null){
                throw new BizException("订单已过期，请重新下单");
            }
            Customer loginCustomer = getLoginCustomer( request);
            if(!loginCustomer.getId().equals(cpsTransOrder.getCustomerId())){
                throw new BizException("请使用被人设备扫码");
            }
            CustomerBank customerBank = customerBankService.getOne(Wraps.<CustomerBank>lbQ().eq(CustomerBank::getBankNum,cpsTransOrder.getCardId()).eq(CustomerBank::getCustomerId,cpsTransOrder.getCustomerId()));

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderId", orderId);
            jsonObject.put("transAmt", cpsTransOrder.getTransAmt());
            jsonObject.put("feeAmt", cpsTransOrder.getFee());
            jsonObject.put("name", customerBank.getAccountName());
            jsonObject.put("payType", "信用卡无卡支付");
            jsonObject.put("orderDate", SystemClockUtil.getLocalDateTime());
            jsonObject.put("bankName", customerBank.getBankName());
            jsonObject.put("cardId", customerBank.getBankNum());
            jsonObject.put("needSms", true);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("短信申请成功");
            vo.setResult(jsonObject);
        } catch (BizException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getMessage());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("订单短信申请");
            log.error("订单短信申请", e);
        }
        return vo;
    }
    @ApiOperation(value = "订单短信申请", httpMethod = "POST")
    @RequestMapping("/applySms")
    @ResponseBody
    public RespVo applySms(HttpServletRequest request,String orderId) {
        RespVo vo = new RespVo();

        try{
            CpsTransOrder cpsTransOrder =(CpsTransOrder) redisService.hget("cps.createQrcode" , orderId);
            if(cpsTransOrder == null){
                throw new BizException("订单已过期，请重新下单");
            }

            Customer loginCustomer = getLoginCustomer( request);
            if(!loginCustomer.getId().equals(cpsTransOrder.getCustomerId())){
                throw new BizException("请使用本人设备扫码");
            }
            if(cpsTransOrder.getId() == null) {
                cpsTransOrder.setRespCode("0100");
                cpsTransOrder.setRespDesc("下单待支付");
                cpsTransOrderService.save(cpsTransOrder);
                messageService.sendQueueByObject(AmqpExchange.REPORT_MESSAGE, OrderReportMQ.builder().orderId(cpsTransOrder.getOrderId())
                        .transAmt(cpsTransOrder.getTransAmt())
                        .orderReportType(OrderReportType.CPS_ORDER)
                        .success(false).build());
                redisService.hset("cps.createQrcode" , cpsTransOrder.getOrderId(),cpsTransOrder, CnswhyConstant.DAY_SECONDS);
            }else{
                if(cpsTransOrder.getStatus() == 1){
                    throw new BizException("该订单已经支付，请重新申请二维码订单");
                }
                cpsTransOrder.setOrderId("CPS" + idGeneratorService.genCommonIdString());
                cpsTransOrderService.updateById(cpsTransOrder);
                redisService.hset("cps.createQrcode" , cpsTransOrder.getOrderId(),cpsTransOrder, CnswhyConstant.DAY_SECONDS);
            }
            cpsTransOrder = cpsTransOrderService.getById(cpsTransOrder.getId());
            if(cpsTransOrder.getStatus() >= 2){
                throw new BizException("该订单已经支付，请重新申请订单");
            }
            CpsChannelInfo cpsChannelInfo = cpsChannelInfoService.getOne(Wraps.<CpsChannelInfo>lbQ().eq(CpsChannelInfo::getChannelId,cpsTransOrder.getChannelId()));
            CustomerBank customerBank = customerBankService.getOne(Wraps.<CustomerBank>lbQ().eq(CustomerBank::getBankNum,cpsTransOrder.getCardId()).eq(CustomerBank::getCustomerId,cpsTransOrder.getCustomerId()));
            CustomerDeviceInfo customerDeviceInfo = customerDeviceInfoService.getOne(Wraps.<CustomerDeviceInfo>lbQ().eq(CustomerDeviceInfo::getCustomerId, loginCustomer.getId()));
            String bindIp = "127.0.0.1";
            String cityName = "深圳市";
            if(customerDeviceInfo != null && StringUtils.isNotBlank(customerDeviceInfo.getCity())){
                bindIp = customerDeviceInfo.getLoginIp();
                cityName = customerDeviceInfo.getCity();
            }
            ResponseEntity responseEntity = hcpayService.subPayApplySms(SubPayApplySmsDto.builder()
                    .amount(cpsTransOrder.getTransAmt().toString())
                    .cardId(cpsTransOrder.getCardId())
                    .cvv(customerBank.getCvv())
                    .expdate(customerBank.getExpdate())
                    .subMerchId(cpsTransOrder.getSubMerchId())
                    .orderId(cpsTransOrder.getOrderId())
                    .bindIp(bindIp)
                    //.cityCode("5840")
                    .cityName(cityName)
                    .phone(customerBank.getMobile())
                    .cvv(customerBank.getCvv())
                    .expdate(customerBank.getExpdate())
                    .notifyUrl(systemService.getCpsNotifyUrl())
                    .build(),cpsChannelInfo.getChannelMerchId(),cpsChannelInfo.getChannelMerchPrivateKey());
            //请求结果：{"code":"0000","data":{"respDesc":"暂不支持该银行卡交易 暂不支持该银行卡交易[-1002]","orderStatus":"03","respCode":"0001"},"message":"成功"}
            try {
                JSONObject jsonObject = JSON.parseObject(responseEntity.getData());
                if("03".equals(jsonObject.getString("orderStatus"))){
                    cpsTransOrder.setStatus(3);
                    cpsTransOrder.setRespCode("0001");
                    cpsTransOrder.setRespDesc(jsonObject.getString("respDesc"));
                    cpsTransOrderService.updateById(cpsTransOrder);
                    return RespVo.fail(jsonObject.getString("respDesc"));
                }
            } catch (Exception e) {
                return RespVo.fail("渠道系统异常");
            }
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("短信申请成功");
        } catch (BizException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getMessage());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("订单短信申请");
            log.error("订单短信申请", e);
        }
        return vo;
    }
    @ApiOperation(value = "申请订单", httpMethod = "POST")
    @RequestMapping("/createQrcode")
    @ResponseBody
    public RespVo createQrcode(HttpServletRequest request,String cardId,String bankAbbr,Long transAmt,String channelType) {
        //channelType little large
        ChannelType channelType1 = null;

        log.info("申请二维码: cardId:{} bankAbbr:{} transAmt:{} channelType:{}",cardId,bankAbbr,transAmt,channelType);
        RespVo vo = new RespVo();
        try {
            if(transAmt == null){
                throw new BizException("请输入交易金额");
            }
            if(StringUtils.isBlank(channelType) || "".equals(channelType) || "LARGE".equals(channelType.toUpperCase())){
                channelType1 = ChannelType.LARGE;
            }else if("LITTLE".equals(channelType.toUpperCase())){
                channelType1 = ChannelType.LITTLE;
            }else{
                channelType1 = ChannelType.LARGE;
            }
            Customer loginCustomer = getLoginCustomer( request);
            loginCustomer = customerService.getById(loginCustomer.getId());
            //查找默认结算卡
            CustomerBank customerBank = customerBankService.getOne(Wraps.<CustomerBank>lbQ().eq(CustomerBank::getCustomerId, loginCustomer.getId())
                .eq(CustomerBank::getIsDefault,1));
            if(customerBank == null){
                throw new BizException("未绑定默认结算卡");
            }
            if(transAmt.compareTo(10000L) < 0 || transAmt.compareTo(2000000L) > 0){
                throw  new BizException("交易金额范围:100-20000");
            }
            if(channelType1.eq(ChannelType.LITTLE) && transAmt.compareTo(100000L) > 0){
                throw  new BizException("交易金额范围:100-1000");
            }
            CpsBankRateSplit cpsBankRateSplit = null;
            try {
                 cpsBankRateSplit = cpsBankRateSplitService.getOne(Wraps.<CpsBankRateSplit>lbQ().eq(CpsBankRateSplit::getBankAbbr,bankAbbr).eq(CpsBankRateSplit::getChannelType,channelType1));
                if(cpsBankRateSplit == null){
                    cpsBankRateSplit = cpsBankRateSplitService.getOne(Wraps.<CpsBankRateSplit>lbQ().eq(CpsBankRateSplit::getBankAbbr,"OTHER").eq(CpsBankRateSplit::getChannelType,channelType1));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException("无渠道可用");
            }
            String channelId = cpsBankRateSplit.getChannelId();
            if(StringUtils.isBlank(bankAbbr)){
                throw new BizException("未选定交易卡号");
            }
            //
            CpsChannelInfo cpsChannelInfo = cpsChannelInfoService.getOne(Wraps.<CpsChannelInfo>lbQ().eq(CpsChannelInfo::getChannelId,channelId));
            if(cpsChannelInfo == null){
                throw new BizException("无效渠道编号");
            }
            //检查进件，进件不存在就进件
            CpsCustomerChannelInfo cpsCustomerChannelInfo = cpsCustomerChannelInfoService.getOne(Wraps.<CpsCustomerChannelInfo>lbQ().eq(CpsCustomerChannelInfo::getCustomerId,loginCustomer.getId())
                .eq(CpsCustomerChannelInfo::getChannelId,channelId)
                .eq(CpsCustomerChannelInfo::getChannelType,channelType1));
            if(cpsCustomerChannelInfo == null){
                //进件

                SubMerchRegisterDto subMerchRegisterDto = SubMerchRegisterDto.builder()
                        .cardId(customerBank.getBankNum())
                        .channelId(channelId)
                        .cityName("深圳")
                        .country("龙岗")
                        .feeRate(68L)
                        .externFee(100L)
                        .idAddress("广东省深圳市龙岗区")
                        .idNo(customerBank.getIdCard())
                        .mccCode("7922")
                        .merchAddress("广东省深圳市龙岗区")
                        .name(customerBank.getAccountName())
                        .phone(customerBank.getMobile())
                        .provinceName("广东")
                        .subMccCode("7922").build();
                SubMerchRegisterResponseDto subMerchRegisterResponseDto = hcpayService.subMerchRegister(subMerchRegisterDto,cpsChannelInfo.getChannelMerchId(),cpsChannelInfo.getChannelMerchPrivateKey());
                cpsCustomerChannelInfo = new CpsCustomerChannelInfo();
                cpsCustomerChannelInfo.setCustomerId(loginCustomer.getId());
                cpsCustomerChannelInfo.setBankNum(customerBank.getBankNum());
                cpsCustomerChannelInfo.setChannelId(channelId);
                cpsCustomerChannelInfo.setAccountName(customerBank.getAccountName());
                cpsCustomerChannelInfo.setMobile(customerBank.getMobile());
                cpsCustomerChannelInfo.setIdCard(customerBank.getIdCard());
                cpsCustomerChannelInfo.setBankAbbr(customerBank.getBankAbbr());
                cpsCustomerChannelInfo.setSubMerchId(subMerchRegisterResponseDto.getSubMerchId());
                cpsCustomerChannelInfo.setFeeRate(68L);
                cpsCustomerChannelInfo.setExternFee(68L);
                cpsCustomerChannelInfo.setChannelType(channelType1);
                cpsCustomerChannelInfoService.save(cpsCustomerChannelInfo);
            }
            CpsBankRate cpsBankRate = null;
            cpsBankRate = cpsBankRateService.getOne(Wraps.<CpsBankRate>lbQ().eq(CpsBankRate::getBankAbbr,bankAbbr).eq(CpsBankRate::getChannelType,channelType1));
            if(cpsBankRate == null){
                cpsBankRate = cpsBankRateService.getOne(Wraps.<CpsBankRate>lbQ().eq(CpsBankRate::getBankAbbr,"OTHER").eq(CpsBankRate::getChannelType,channelType1));
                if(cpsBankRate == null){
                    throw new BizException("该银行费率未设定");
                }
            }
            if(cpsBankRate.getExternFee().equals(cpsCustomerChannelInfo.getExternFee()) && cpsBankRate.getFeeRate().equals(cpsCustomerChannelInfo.getFeeRate())){

            }else{
                SubMerchUpgradeDto subMerchUpgradeDto = SubMerchUpgradeDto.builder().build();
                subMerchUpgradeDto.setType("2");
                subMerchUpgradeDto.setFeeRate(cpsBankRate.getFeeRate());
                subMerchUpgradeDto.setExternFee(cpsBankRate.getExternFee());
                subMerchUpgradeDto.setSubMerchId(cpsCustomerChannelInfo.getSubMerchId());
                hcpayService.subMerchUpgrade(subMerchUpgradeDto,cpsChannelInfo.getChannelMerchId(),cpsChannelInfo.getChannelMerchPrivateKey());
                cpsCustomerChannelInfo.setFeeRate(cpsBankRate.getFeeRate());
                cpsCustomerChannelInfo.setExternFee(cpsBankRate.getExternFee());
                cpsCustomerChannelInfoService.updateById(cpsCustomerChannelInfo);
            }
            if(!cpsCustomerChannelInfo.getBankNum().equals(customerBank.getBankNum())){
                SubMerchUpgradeDto subMerchUpgradeDto = SubMerchUpgradeDto.builder().build();
                subMerchUpgradeDto.setType("1");
                subMerchUpgradeDto.setCardId(customerBank.getBankNum());
                subMerchUpgradeDto.setPhone(customerBank.getMobile());
                subMerchUpgradeDto.setSubMerchId(cpsCustomerChannelInfo.getSubMerchId());
                hcpayService.subMerchUpgrade(subMerchUpgradeDto,cpsChannelInfo.getChannelMerchId(),cpsChannelInfo.getChannelMerchPrivateKey());
                cpsCustomerChannelInfo.setBankNum(customerBank.getBankNum());
                cpsCustomerChannelInfo.setMobile(customerBank.getMobile());
                cpsCustomerChannelInfoService.updateById(cpsCustomerChannelInfo);
            }
            vo.setCode(RespVo.CODE_SUCCESS);
            BigDecimal feeAmt = BigDecimal.valueOf(transAmt * cpsBankRate.getFeeRate()).divide(BigDecimal.valueOf(CnswhyConstant.rateMode)).setScale(0, BigDecimal.ROUND_HALF_UP);

            CpsTransOrder cpsTransOrder = CpsTransOrder.builder()
                    .orderId(idGeneratorService.genCommonIdString())
                    .cardId(cardId)
                    .channelId(channelId)
                    .customerId(loginCustomer.getId())
                    .mobile(loginCustomer.getLoginName())
                    .settDate(SystemClockUtil.getSettDateyyyyMMdd())
                    .transAmt(transAmt)
                    .feeRate(cpsBankRate.getFeeRate())
                    .externFee(cpsBankRate.getExternFee())
                    .transFee(feeAmt.longValue())
                    .channelType(channelType1)
                    .custName(loginCustomer.getVerifyName())
                    .fee(feeAmt.longValue()  + cpsBankRate.getExternFee())
                    .subMerchId(cpsCustomerChannelInfo.getSubMerchId())
                    .bankAbbr(cpsBankRate.getBankAbbr())
                    .status(0).build();
            redisService.hset("cps.createQrcode" , cpsTransOrder.getOrderId(),cpsTransOrder, CnswhyConstant.DAY_SECONDS);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderId", cpsTransOrder.getOrderId());
            vo.setResult(jsonObject);
            //vo.setResult(pageList);
        } catch (BizException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getMessage());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("申请订单失败");
            log.error("申请订单失败", e);
        }
        return vo;
    }


    @ApiOperation(value = "订单确认", httpMethod = "POST")
    @RequestMapping("/notify/{requestId}")
    public String notify(HttpServletRequest request,@PathVariable String requestId) {
        try{
            CpsTransOrder cpsTransOrder =(CpsTransOrder) redisService.hget("cps.createQrcode" , requestId);
            if(cpsTransOrder == null){
                return "success";
            }
            CpsOrderQueryMQ cpsOrderQueryMQ = CpsOrderQueryMQ.builder()
                    .cpsId(cpsTransOrder.getId())
                    .queryTimes(0L).build();
            messageService.sendAndQueryTimes(AmqpExchange.CPS_ORDER_QUERY_MESSAGE, cpsOrderQueryMQ, cpsOrderQueryMQ.getQueryTimes());

        } catch (BizException e) {
        } catch (Exception e) {
        }
        return "success";
    }

}
